const router = require('express').Router();
const stuModel = require('../model/collections/stu');
router.get('/home', async (req, res) => {
  // 查询数据
  const stus = await stuModel.find().sort({_id: -1});

  res.render('home', {
    stus
  })
})
// 新增学生
router.post('/addStu', (req,res)=> {
  stuModel.insertMany(req.body).then(ret=> {
    res.send({
      code: 200,
      msg: '新增成功'
    })
  }).catch(err => {
    res.send({
      code: 400,
      msg: '新增失败'
    })
  })
})

// 删除学生

router.delete('/delItem', (req, res) => {
  const {_id} = req.query;
  stuModel.deleteOne({
    _id
  }).then(ret => {
    res.send({
      code: 200,
      msg: '删除成功'
    })
  }).catch(err => {
    res.send({
      code: 400,
      msg: '删除失败'
    })
  })
  
})

// 更新
router.put('/updateStu', (req, res) => {
 stuModel.updateOne(
  {
    _id: req.body._id
  },
  {
    stuAge: req.body.stuAge
  }
 ).then(ret => {
    res.send({
      code: 200,
      msg: '更新成功'
    })
  }).catch(err => {
    res.send({
      code: 400,
      msg: '更新失败'
    })
  })
  
})
module.exports = router;